package cn.jinjimi.app.main.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import cn.jinjimi.base.util.DESEncryptUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.TimeCount;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.LoginEvent;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.domain.data.dto.ProfileDTO;
import cn.jinjimi.domain.data.dto.VerifyResultDTO;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.UserStore;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.dialog.VerifyCodeDialog;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.MTextWatcher;
import cn.jinjimi.app.main.widget.PhoneBaseEditTextView;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.InputStream;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;
import okhttp3.Headers;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by HANER on 15/4/13.
 */
public class BindPhoneFragment extends BaseFragment implements View.OnClickListener {
    private PhoneBaseEditTextView phone;
    private Button cleanPhone;
    private EditText valid;
    private Button cleanValid;
    private TextView getValid;
    private TextView submit;
    private VerifyCodeDialog mDialog;

    private TimeCount timeCount;
    private ProfileDTO agent;
    private String unionid;
    private String openid;
    private int mSource = 0;

    public static BindPhoneFragment newInstance(String unionId, String openId) {
        BindPhoneFragment fragment = new BindPhoneFragment();
        Bundle args = new Bundle();
        args.putString("unionid", unionId);
        args.putString("openid", openId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_bind_phone;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        getActivity().setTitle(R.string.title_bind_phone);

        unionid = getArguments().getString("unionid");
        openid = getArguments().getString("openid");
        //手机号
        phone = (PhoneBaseEditTextView) findView().findViewById(R.id.et_phone);
        //清除手机号码
        cleanPhone = (Button) findView().findViewById(R.id.bt_clean_phone_number);
        //验证码
        valid = (EditText) findView().findViewById(R.id.valid_code);
        //清除验证码
        cleanValid = (Button) findView().findViewById(R.id.clean_valid_code);
        //获取验证码
        getValid =  findView().findViewById(R.id.get_valid_code);
        //点击提交
        submit = findView().findViewById(R.id.bt_submit);
    }

    protected void initListener() {
        cleanPhone.setOnClickListener(this);
        cleanValid.setOnClickListener(this);
        getValid.setOnClickListener(this);
        submit.setOnClickListener(this);

        phone.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 手机号框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanPhone.setVisibility(View.VISIBLE);
                } else {
                    cleanPhone.setVisibility(View.INVISIBLE);
                }
            }
        });
        valid.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 验证码框变化时判断框内是否为空，是就设置clean显示
                if (!TextUtils.isEmpty(s)) {
                    cleanValid.setVisibility(View.VISIBLE);
                } else {
                    cleanValid.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_valid_code:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    getVerifyWord(mSource);
                }
                break;
            case R.id.bt_clean_phone_number:
                phone.setText("");
                break;
            case R.id.clean_valid_code:
                valid.setText("");
                break;
            case R.id.bt_submit:
                if (StringUtils.checkPhoneNum(getActivity(), phone)) {
                    if (StringUtils.checkValidCode(getActivity(), valid)) {
                        submit();
                    }
                }
                break;
        }
    }

    /**
     * 提交登录请求
     */
    private void submit() {
        UserController.loginByOther(phone.getRealPhoneNum(), valid.getText().toString().trim(), openid, unionid);
        ((LoginActivity) getActivity()).showLoadingIndicator();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        ((LoginActivity) getActivity()).hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:

                agent = event.data;
                phone.savePhoneNum();
                dealWithStatus(agent.getStatus());
                break;
            case DataEvent.FAIL:
                if (event.error == 400) {
                    ToastUtils.toastMessage(getActivity(), (String) event.msg);
                } else {
                    ToastUtils.toastMessage(getActivity(), getString(R.string.bind_fail));
                }
                break;
        }
    }

    /**
     * 获取验证码
     *
     * @param source
     */
    private void getVerifyWord(final int source) {

    }

    /**
     * 显示验证码弹框
     *
     * @param imgStream
     * @param captcha
     * @param source
     */
    private void showVerifyDialog(InputStream imgStream, final String captcha, final int source) {
        if (mDialog == null) {
            mDialog = new VerifyCodeDialog(getContext());
        }
        mDialog.setVerifyImg(imgStream).setTopListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerifyWord(source);
            }
        }).setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismissDialog();
                mDialog.clear();
            }
        }).setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String verifyCode = mDialog.getVerifyCode();
                if (StringUtils.isEmpty(verifyCode)) {
                    ToastUtil.showCusToast(getContext(), getActivity().getResources()
                            .getString(R.string.me_verify_error), ToastUtils.FAIL);
                } else {
                    mDialog.setLoading(true);
                    sendVerify(captcha, source, verifyCode);
                }
            }
        });
        mDialog.showDialog(true);
    }

    /**
     * 发送验证码
     *
     * @param captcha
     * @param source
     * @param verifyCode
     */
    private void sendVerify(final String captcha, final int source, final String verifyCode) {

    }


    /**
     * 根据返回的状态处理
     */
    private void dealWithStatus(int i) {

    }

    @Override
    public void onDestroyView() {
        if (mDialog != null) {
            mDialog.dismissDialog();
            mDialog = null;
        }
        super.onDestroyView();
    }
}
